<template>
    <div class="detail-container">
      <!-- 物品清单 -->
      <div class="section-title">
        <span class="title-bar"></span>
        物品清单
      </div>
  
      <!-- 物品列表 -->
      <div class="goods-list">
        <template v-if="applyInfo.applyStatus == 4 && entrance != 2">
          <van-checkbox-group v-model="putInStorageList" @change="onChange">
            <div v-for="(item, index) in list" :key="index" class="goods-item">
              <div class="goods-header">
                <div class="goods-name">
                  <van-checkbox 
                    :name="item.suppliesId"
                    :disabled="item.receiveStatus == 1"
                  >
                    {{ item.goodsName }}
                  </van-checkbox>
                </div>
                <div class="goods-price">单价：￥{{ item.unitPrice }}元/{{ item.goodsUnit }}</div>
              </div>
              <div class="goods-info">
                <div>申请数量：{{ item.goodsAmount }}{{ item.goodsUnit }}</div>
                <div>
                  <span>金额：</span>
                  <span class="amount">￥{{ item.amount }}</span>
                </div>
              </div>
              <div class="goods-remark">备注：{{ item.remark }}</div>
            </div>
          </van-checkbox-group>
        </template>
        <template v-else>
          <div v-for="(item, index) in list" :key="index" class="goods-item">
            <div class="goods-header">
              <div class="goods-name">{{ item.goodsName }}</div>
              <div class="goods-price">单价：￥{{ item.unitPrice }}元/{{ item.goodsUnit }}</div>
            </div>
            <div class="goods-info">
              <div>申请数量：{{ item.goodsAmount }}{{ item.goodsUnit }}</div>
              <div>
                <span>金额：</span>
                <span class="amount">￥{{ item.amount }}</span>
              </div>
            </div>
            <div class="goods-remark">备注：{{ item.remark }}</div>
          </div>
        </template>
      </div>
  
      <!-- 合计金额 -->
      <div class="total-amount">
        合计金额：<span>￥{{ applyInfo.amount }}</span>
      </div>
  
      <!-- 审批操作区 -->
      <template v-if="taskId && applyInfo.applyStatus == 1">
        <template v-if="!detailInfo.ifCurrentUserApproved">
          <div class="section-title">
            <span class="title-bar"></span>
            审批内容
          </div>
          <div class="approval-input">
            <van-field
              v-model="result"
              type="textarea"
              maxlength="200"
              placeholder="说点什么吧"
              show-word-limit
              rows="4"
            />
          </div>
          <div class="button-group">
            <van-button 
              class="reject-btn" 
              type="danger" 
              :loading="loading"
              @click="handConsent($event, '3')"
            >
              驳回
            </van-button>
            <van-button 
              type="primary" 
              :loading="loading"
              @click="handConsent($event, '2')"
            >
              通过
            </van-button>
          </div>
        </template>
      </template>
  
      <!-- 其他操作按钮 -->
      <template v-else>
        <div class="button-group" v-if="entrance != 2">
          <van-button 
            v-if="applyInfo.applyStatus == 4" 
            type="primary" 
            block
            @click="handImport"
          >
            入库
          </van-button>

          <van-button 
            v-if="applyInfo.applyStatus == 1" 
            type="warning" 
            block
            @click="canclePosted"
          >
            撤回
          </van-button>
  
          <template v-if="applyInfo.applyStatus == 3 || applyInfo.applyStatus == 5">
            <van-button 
              type="warning"
              @click="handRetry"
            >
              重报
            </van-button>
            <van-button 
              type="danger"
              @click="handDelete"
            >
              删除
            </van-button>
          </template>
        </div>
      </template>
    </div>
  </template>
  
  <script>
  // import approval from '@/components/approvalProcess/index'
  import { Toast } from 'vant'
  import { 
    getApplyRecordDetails, 
    handlePurchase, 
    putInStorage,
    cancelPurchase,
    retryPurchase,
    deletePurchase
  } from '@/api/purchaseControlDetail'
  
  export default {
    name: 'PurchaseControlDetail',
    
    components: {
      // approval
    },
  
    data() {
      return {
        list: [],
        detailId: 0,
        taskId: 0,
        applyInfo: {
          applyStatus: 0,
          amount: ''
        },
        result: '',
        entrance: '',
        putInStorageList: [],
        loading: false,
        detailInfo: {
          ifCurrentUserApproved: ''
        },
        procId:'',
        approvalInfo: '',
        officeSuppliesIds:[]
      }
    },
  
    created() {
      const { entrance = '', id = 0, taskId = 0 } = this.$route.query
      this.entrance = entrance
      this.detailId = id
      this.taskId = taskId
      this.loadDetailData()
    },
  
    methods: {
      loadDetailData() {
        const params = {
                applyId: this.$route.query.id,
                openSessionId: JSON.parse(localStorage.getItem('user'))?.openSessionId
            }
        
         getApplyRecordDetails(params)
          .then(res => {
            if (res.code === 200) {
              const data = res.data
              data.departName = data.apply.departName
              data.applyUserName = data.apply.applyName
              data.applyTime = data.apply.applyTime
              data.approvalList = data.approvalInfo
              data.approvalList.splice(0, 1)
              data.approvalList.forEach(item => {
                item.result = item.state
                item.name = item.userName
                item.endTime = item.state != 1 ? item.date : ''
              })
  
              this.detailInfo = data
              this.applyInfo = data.apply
              this.list = data.applyDetails
              this.procId = this.applyInfo.procId
              this.approvalInfo = data.approvalInfo
              this.officeSuppliesIds = data.applyDetails.map(item => {return item.suppliesId})
              console.log(res);
            } else {
              Toast.fail(res.message || '获取详情失败')
            }
          })
          .catch(err => {
            console.error(err)
            Toast.fail('获取详情失败')
          })
      },
  
      handConsent(e, value) {
        if (this.loading) return
        
        this.loading = true
        const params = {
          openSessionId: JSON.parse(localStorage.getItem('user'))?.openSessionId,
          taskId: Number(this.taskId),
          comment: this.result,
          result: Number(value)
        }
  
        handlePurchase(params)
          .then(res => {
            this.loading = false
            if (res.code === 200) {
              Toast.success(res.message)
              this.$router.back()
            } else {
              Toast.fail(res.message)
            }
          })
          .catch(err => {
            console.error(err)
            this.loading = false
            Toast.fail('操作失败')
          })
      },
  
      onChange(value) {
        this.putInStorageList = value
        console.log(this.putInStorageList)
      },
  
      handImport() {
       // 修改后的代码
        if (this.officeSuppliesIds.length === 0) {
        Toast('请选择要入库的物品')
        return
        }
        const params = {
          openSessionId: JSON.parse(localStorage.getItem('user'))?.openSessionId,
          applyId: this.detailId,
          officeSuppliesIds: this.officeSuppliesIds
        }
        putInStorage(JSON.parse(localStorage.getItem('user'))?.openSessionId,this.detailId,this.officeSuppliesIds)
          .then(res => {
            if (res.code === 200) {
              Toast.success(res.message)
              this.$router.back()
            } else {
              Toast.fail(res.message)
            }
          })
          .catch(err => {
            console.error(err)
            Toast.fail('操作失败')
          })
      },
  
      canclePosted() {
        const params = {
          openSessionId: JSON.parse(localStorage.getItem('user'))?.openSessionId,
          applyId: this.detailId,
          procId: this.procId,
        }
  
        cancelPurchase(params)
          .then(res => {
            if (res.code === 200) {
              Toast.success(res.message)
              this.$router.back()
            } else {
              Toast.fail(res.message)
            }
          })
          .catch(err => {
            console.error(err)
            Toast.fail('操作失败')
          })
      },
  
      handRetry() {
        const params = {
          openSessionId: JSON.parse(localStorage.getItem('user'))?.openSessionId,
          applyId: this.detailId
        }
  
        retryPurchase(params)
          .then(res => {
            if (res.code === 200) {
              Toast.success(res.message)
              this.$router.back()
            } else {
              Toast.fail(res.message)
            }
          })
          .catch(err => {
            console.error(err)
            Toast.fail('操作失败')
          })
      },
  
      handDelete() {
        const params = {
          openSessionId: JSON.parse(localStorage.getItem('user'))?.openSessionId,
          applyId: this.detailId
        }
  
        deletePurchase(params)
          .then(res => {
            if (res.code === 200) {
              Toast.success(res.message)
              this.$router.back()
            } else {
              Toast.fail(res.message)
            }
          })
          .catch(err => {
            console.error(err)
            Toast.fail('操作失败')
          })
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .detail-container {
    min-height: 100vh;
    padding: 20px;
    background-color: #f5f5f5;
  
    .section-title {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      font-size: 16px;
      font-weight: bold;
  
      .title-bar {
        width: 4px;
        height: 16px;
        margin-right: 8px;
        background: #3669f8;
        border-radius: 2px;
      }
    }
  
    .goods-item {
      margin-bottom: 15px;
      padding: 15px;
      background: #fff;
      border-radius: 8px;
      border: 1px solid #ddd;
  
      .goods-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
      }
  
      .goods-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        color: #666;
      }
  
      .goods-remark {
        color: #666;
      }
  
      .amount {
        color: #3c84ea;
      }
    }
  
    .total-amount {
      margin: 20px 0;
      text-align: right;
      font-size: 16px;
      font-weight: bold;
  
      span {
        color: #3c84ea;
      }
    }
  
    .approval-input {
      margin: 15px 0;
    }
  
    .button-group {
      display: flex;
      justify-content: space-between;
      margin: 20px 0;
      gap: 15px;
  
      .van-button {
        flex: 1;
      }
    }
  }
  </style>